<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
    <el-form-item label="网格名称" prop="gridId">
      <el-select v-model="formData.gridId" placeholder="请输入网格名称" @change="handleGridChange" :disabled="true">
        <el-option v-for="item in gridList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="名称" prop="name">
      <!-- 先做成人工输入，后续考虑自动生成？ -->
      <el-input v-model="formData.name" placeholder="请输入名称" :disabled="true"/>
    </el-form-item>
    <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" :disabled="true">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_AQI_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    <div class="aqi-box">
      <div class="ab-left">
        <el-form-item label="填报人" prop="userName">
          <!-- 获取当前登录用户，如果是网格员，回显填报人 -->
          <el-input v-model="formData.userName" placeholder="请输入填报人" :disabled="true"/>
        </el-form-item>
        <el-form-item label="细颗粒物（PM2.5）" prop="pm25">
          <el-input v-model="formData.pm25" placeholder="请输入细颗粒物（PM2.5）" :disabled="true">
            <template #append>µg/m3</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二氧化硫（SO2）" prop="so2">
          <el-input v-model="formData.so2" placeholder="请输入二氧化硫（SO2）" :disabled="true">
            <template #append>µg/m3</template>
          </el-input>
        </el-form-item>
        <el-form-item label="一氧化碳（CO）" prop="co">
          <el-input v-model="formData.co" placeholder="请输入一氧化碳（CO）" :disabled="true">
            <template #append>mg/m3</template>
          </el-input>
        </el-form-item>
        <el-divider />
        <el-form-item label="AQI" prop="aqi">
          <el-input v-model="formData.aqi" placeholder="AQI自动计算" :disabled="true"/>
        </el-form-item>
        <el-form-item label="空气质量指数级别" prop="aqiLevel">
          <el-radio-group v-model="formData.aqiLevel" :disabled="true">
            <el-radio
              v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_AQI_LEVEL)"
              :key="String(dict.value)"
              :label="dict.value"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="反馈信息" prop="description">
          <el-input type="textarea" resize="vertical" :autosize="{ minRows: 2, maxRows: 4 }" v-model="formData.description" :disabled="true" />
        </el-form-item>
      </div>
      <div class="ab-separate"></div>
      <div class="ab-right">
        <!-- 如果是网格员，显示获取当前登录用户 -->
        <el-form-item label="网格员" prop="gridUserName">
          <el-input v-model="formData.gridUserName" placeholder="请输入网格员" :disabled="true"/>
        </el-form-item>
        <el-form-item label="细颗粒物（PM2.5）" prop="pm25Confirm">
          <el-input v-model="formData.pm25Confirm" placeholder="请输入细颗粒物（PM2.5）" :disabled="formType === 'viewComparison'" @change="handlePm25ConfirmChange">
            <template #append>µg/m3</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二氧化硫（SO2）" prop="so2Confirm">
          <el-input v-model="formData.so2Confirm" placeholder="请输入二氧化硫（SO2）" :disabled="formType === 'viewComparison'" @change="handleSo2ConfirmChange">
            <template #append>µg/m3</template>
          </el-input>
        </el-form-item>
        <el-form-item label="一氧化碳（CO）" prop="coConfirm">
          <el-input v-model="formData.coConfirm" placeholder="请输入一氧化碳（CO）" :disabled="formType === 'viewComparison'" @change="handleCoConfirmChange">
            <template #append>mg/m3</template>
          </el-input>
        </el-form-item>
        <el-divider />
        <el-form-item label="AQI" prop="aqiConfirm">
          <el-input v-model="formData.aqiConfirm" placeholder="AQI自动计算" :disabled="true"/>
        </el-form-item>
        <el-form-item label="空气质量指数级别" prop="aqiLevelConfirm">
        <el-radio-group v-model="formData.aqiLevelConfirm" :disabled="true">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_AQI_LEVEL)"
            :key="String(dict.value)"
            :label="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
        <el-form-item label="反馈信息" prop="descriptionConfirm">
          <el-input type="textarea" resize="vertical" :autosize="{ minRows: 2, maxRows: 4 }" v-model="formData.descriptionConfirm" placeholder="请输入反馈信息"  :disabled="formType === 'viewComparison'"/>
        </el-form-item>
      </div>
    </div>
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="formType === 'secondConfirm'">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { AqiApi, AqiVO } from '@/api/envir/aqi'
import { GridApi, GridVO } from '@/api/envir/grid'
import { useUserStore } from '@/store/modules/user'

/** AQI 表单 */
defineOptions({ name: 'AqiConfirmForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore()

const userId = computed(() => userStore.user.id)
const userName = computed(() => userStore.user.nickname ?? 'Admin')

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：secondConfirm - 二次确认；viewComparison - 查看对比
const formData = ref({
  id: undefined,
  gridId: undefined,
  gridName: '',
  userId: userId.value,
  userName: userName.value,
  gridUserId: undefined,
  gridUserName: undefined,
  name: undefined,
  pm25: undefined,
  so2: undefined,
  co: undefined,
  aqiLevel: undefined,
  description: undefined,
  pm25Confirm: undefined,
  so2Confirm: undefined,
  coConfirm: undefined,
  aqiLevelConfirm: undefined,
  descriptionConfirm: undefined,
  aqi: undefined,
  aqiConfirm: undefined,
  status: 0
})
const formRules = reactive({
  gridId: [{ required: true, message: '网格ID不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  // gridUserId: [{ required: true, message: '网格用户ID不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  pm25: [{ required: true, message: '细颗粒物（PM2.5）不能为空', trigger: 'blur' }],
  so2: [{ required: true, message: '二氧化硫（SO2）不能为空', trigger: 'blur' }],
  co: [{ required: true, message: '一氧化碳（CO）不能为空', trigger: 'blur' }],
  aqiLevel: [{ required: true, message: '空气质量指数级别不能为空', trigger: 'blur' }],
  // description: [{ required: true, message: '反馈信息不能为空', trigger: 'blur' }],
  pm25Confirm: [{ required: true, message: '细颗粒物（PM2.5）-确认值不能为空', trigger: 'blur' }],
  so2Confirm: [{ required: true, message: '二氧化硫（SO2）-确认值不能为空', trigger: 'blur' }],
  coConfirm: [{ required: true, message: '一氧化碳（CO）-确认值不能为空', trigger: 'blur' }],
  aqiLevelConfirm: [{ required: true, message: '空气质量指数级别-确认值不能为空', trigger: 'blur' }],
  // descriptionConfirm: [{ required: true, message: '反馈信息）-确认值不能为空', trigger: 'blur' }],
  // status: [{ required: true, message: '状态(0-待指派 1-已指派 2-已完成)不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const gridList = ref([] as GridVO[]) // 

const handleGridChange = (gridId: number) => {
  const grid = gridList.value.find(item => item.id === gridId)
  if (grid) {
    formData.value.gridName = grid.name
  }
}

const handlePm25ConfirmChange = () => {
  formData.value.aqiConfirm = undefined
  formData.value.aqiLevelConfirm = undefined
  calculateAqi()
}

const handleSo2ConfirmChange = () => {
  formData.value.aqiConfirm = undefined
  formData.value.aqiLevelConfirm = undefined
  calculateAqi()
}

const handleCoConfirmChange = () => {
  formData.value.aqiConfirm = undefined
  formData.value.aqiLevelConfirm = undefined
  calculateAqi()
}

const calculateAqi = async() => {
  const pm25Confirm = formData.value.pm25Confirm
  const so2Confirm = formData.value.so2Confirm
  const coConfirm = formData.value.coConfirm
  if (pm25Confirm && so2Confirm && coConfirm) {
    const data = {
      pm25: pm25Confirm, 
      so2: so2Confirm,
      co: coConfirm
    } as unknown as AqiVO
    const aqi = await AqiApi.calculateAqi(data)
    formData.value.aqiConfirm = aqi.aqi
    formData.value.aqiLevelConfirm = aqi.aqiLevel
  }
}


/** 打开弹窗 */
const open = async (type: string, id: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AqiApi.getAqi(id)
    } finally {
      formLoading.value = false
    }
  }
   // 获得网格的列表
  gridList.value = await GridApi.getSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AqiVO
    Object.assign(data, {
      status: 2
    })
    await AqiApi.updateAqi(data)
    message.success(t('common.updateSuccess'))

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    gridId: undefined,
    gridName: '',
    userId: userId.value,
    userName: userName.value,
    gridUserId: undefined,
    gridUserName: undefined,
    name: undefined,
    pm25: undefined,
    so2: undefined,
    co: undefined,
    aqiLevel: undefined,
    description: undefined,
    pm25Confirm: undefined,
    so2Confirm: undefined,
    coConfirm: undefined,
    aqiLevelConfirm: undefined,
    descriptionConfirm: undefined,
    aqi: undefined,
    aqiConfirm: undefined,
    status: 0
  }
  formRef.value?.resetFields()
}
</script>
<style scoped lang="scss">
.aqi-box{
  display: flex;
  .ab-left
  {
    flex: 1;
  }
  .ab-right
  {
    flex: 1;
  }
}

</style>